package cn.kevinking.auth.service.impl;

import cn.kevinking.auth.domain.LoginUserAdapter;
import cn.kevinking.auth.exception.InvalidLoginException;
import cn.kevinking.auth.model.dto.UserLoginDTO;
import cn.kevinking.auth.model.vo.BfzAuthenticationVO;
import cn.kevinking.auth.service.IBfzAuthService;
import cn.kevinking.auth.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * authentication service impl
 *
 * @author kevinking
 * @since 13 Apr 2025
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class BfzAuthServiceImpl implements IBfzAuthService {

	private final AuthenticationManager authenticationManager;

	@Override
	public BfzAuthenticationVO loginByUsernamePassword(UserLoginDTO loginDTO) {
		UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword());
		// will call dao methods defined in IBfzUserService:loadUserByUsername
		Authentication authResult = authenticationManager.authenticate(auth);
		if (authResult == null) {
			throw new InvalidLoginException("Login failed!");
		}
		if (authResult.getPrincipal() instanceof LoginUserAdapter adapter) {
			// use current user info to create jwt token
			String token = JwtUtils.createToken(adapter.getUser());
			// save in redis

		} else {
			throw new InvalidLoginException("Login failed!");
		}
		return null;
	}
}
